package cn.wit.test;

/**
 * 541.翻转字符串(有问题)
 * 
 * @author 16604
 *
 */
public class DemoReverseChar {
	public static void main(String[] args) {
		String s = "abcdefg";
		int k = 5;
		System.out.println(reverseStr(s, k));
	}

	public static String reverseStr(String s, int k) {
		
		int length = s.length();
		int business = length / (2 * k);// 商
		int remainder = length - business * k * 2;// 余数
		int m = 0;
		int sta = 0;
		// System.out.println(business);
		// 将字符串转变为可操作得
		StringBuilder sb = new StringBuilder(s);

		if (length <= k) {
			sb.reverse();
			s = sb.toString().toLowerCase();
			return s;
		}
		
		// System.out.println(length);
		if (length < k * 2 && length > k) {
			{
				for (int i = 0; i <= business; i++) {
					for (m = 0, sta = business * k * 2; m < k / 2; m++) {// 翻转前K个字符
						if ((sta + k - 1 + m * 2) >= length || (sta >= length)) {
							break;
						}

						char temp = sb.charAt(sta);
						sb.setCharAt(sta, s.charAt(sta + k - 1 - m * 2));
						sb.setCharAt(sta + k - 1 - m * 2, temp);
						
						
						sta++;
					}
				}
			}
		}
		if (length >= k * 2) {

			for (int i = 0; i <= business; i++) {

				for (m = 0, sta = i * k * 2; m < k / 2; m++) {// 翻转每2K个字符的前K个字符
					// sb.setCharAt(sta, s.charAt(sta+k-1+m*2));
					// sta++;
					// 为了防止数组越界
					if ((sta + k - 1 + m * 2) >= length || (sta >= length)) {
						break;
					}
					char temp = sb.charAt(sta);
					sb.setCharAt(sta, s.charAt(sta + k - 1 + m * 2));
					sb.setCharAt(sta + k - 1 + m * 2, temp);
					sta++;
				}
			}
		}

		// System.out.println(k/2);
		// System.out.println(s);
		// System.out.println(sb);
		// StringBuilder转换为String类型
		s = sb.toString().toLowerCase();
		return s;
	}

}
